package com.qf.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {
    //加注释了
    private static final String FORWARD="FORWARD";
    private static final String REDIRECT="REDIRECT";
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action=request.getParameter("action");//getGoods
        /*if("checkUsername".equals(action)){
            checkUsername(request,response);
        }else if("userRegister".equals(action)){
            userRegister(request,response);
        }else if("activate".equals(action)){
            activate(request,response);
        }else if("login".equals(action)){

        }*/


        Class c = this.getClass();

        try {
            Method declaredMethod = c.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);


            Object invoke = declaredMethod.invoke(this, request, response);
          if(invoke!=null){
              String result= (String) invoke;
//FORWARD:error.jsp
              if(result.startsWith(FORWARD)){
                  int i = result.indexOf(":");
                  String str=result.substring(i+1);
                  request.getRequestDispatcher(str).forward(request,response);
              }else if(result.startsWith(REDIRECT)){
                  //"REDIRECT:login.jsp"
                  int i = result.indexOf(":");
                  String str=result.substring(i+1);
                  response.sendRedirect(str);
              }else{
                  response.getWriter().print(result);
              }
          }

        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
